from PyQt5.QtWidgets import QDialog, QMessageBox
from PyQt5.QtCore import QStringListModel
import UI.type_manager_UI as typeManagerUI
import json


class TypeManagerUi(QDialog, typeManagerUI.Ui_Form):
    def __init__(self):
        super(TypeManagerUi, self).__init__()
        self.setupUi(self)
        self.typeLst = list()
        try:
            with open('typeData.json', 'r') as f:
                self.typeLst = json.load(f)
        except json.JSONDecodeError as err:
            print("JSONDecodeError: {0}".format(err))
        except IOError as err:
            print("IOError: {0}".format(err))
        self.listViewItemModel = QStringListModel(self)
        self.listViewItemModel.setStringList(self.typeLst)
        self.listView.setModel(self.listViewItemModel)

    def remove(self):
        buttons = QMessageBox.StandardButton
        rlt = QMessageBox.question(self, '警告', '确认删除所选项目?', buttons.Yes | buttons.Ignore, buttons.Ignore)
        if rlt == buttons.Ignore:
            return
        indexes = self.listView.selectedIndexes()
        for index in indexes:
            self.typeLst.pop(index.row())
            self.listViewItemModel.setStringList(self.typeLst)
        self.save()

    def add(self):
        string = self.typeNameLineEdit.text()
        if string == '':
            QMessageBox.critical(self, '错误', '货物类型名不能重复也不能为空!')
            return
        for item in self.typeLst:
            if item == string:
                QMessageBox.critical(self, '错误', '货物类型名不能重复也不能为空!')
                return
        self.typeLst.append(string)
        self.listViewItemModel.setStringList(self.typeLst)
        self.typeNameLineEdit.setText('')
        self.save()

    def save(self):
        try:
            with open('typeData.json', 'w') as f:
                json.dump(self.typeLst, f)
        except json.JSONDecodeError as err:
            print("JSONDecodeError: {0}".format(err))
        except ValueError as err:
            print("ValueError: {0}".format(err))
